﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExchangeClient.Abstractions;
using ExchangeClient.Abstractions.Model;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.Formula.Functions;
using Org.BouncyCastle.Asn1.X509;
using RestSharp;
using SyncService.Abstractions.Events;
using SyncService.Abstractions.Services;
using System.Composition;
using System.Security.AccessControl;
using System.Text.Json;
using System.Text.Json.Nodes;
using static Org.BouncyCastle.Bcpg.Attr.ImageAttrib;
using SyncService.Core.Model;
using System.Reflection;

namespace SyncService.Core.Services
{

    [Export(typeof(ISyncService))]
    [ExportMetadata(YdConstants.ID, "SapTransferReceive")]
    public class SapTransferReceiveService : SyncServiceBase
    {
        private IMemoryCache? _cache = null;
        private ILogger<SapTransferReceiveService> _logger = null;

        protected override string NotifyGroupName => throw new NotImplementedException();

        public SapTransferReceiveService() : base(YdConstants.YIDEA, "Sap", "")
        {
        }
        protected override void InitializeContext()
        {
            base.SetMultiCallback();
            base.InitializeContext();
            _cache = Resolver.Resolve<IMemoryCache>();
            _logger = Resolver.Resolve<ILogger<SapTransferReceiveService>>();
        }

        public override void Execute(dynamic? state)
        {

            string jsonText = Convert.ToString(state.Body);
            var ResultContent = JsonSerializer.Deserialize<JsonObject>(jsonText);
            var resultArray = ResultContent["result"] as JsonArray;
            _logger.LogInformation("开始处理SAP回调数据 " + jsonText);


            var serialNo = ResultContent["SerialNo"]!.ToString();
            string code = serialNo.Substring(0, 3);

            //Thread.Sleep(60000);

            Transfer transfer = new Transfer();
            var formId = UserDefines.First(x => x.Name == "调拨自定义表单");
            var VformId = UserDefines.First(x => x.Name == "V测试资产调拨单");
            var VTestTransferTypeField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调拨类型");
            var inComanyField = ExtendFields.First(x => x.ObjectType == 49 && x.Name == "调入公司码");
            var outComanyField = ExtendFields.First(x => x.ObjectType == 49 && x.Name == "调出公司码");
            var assetField = ExtendFields.First(x => x.ObjectType == 49 && x.Name == "资产列表");
            var assetVTestTableField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表");
            var assetAllotField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调拨状态");
            var assetVTestAllotField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试公司间调拨状态");
            var TRAformId = UserDefines.First(x => x.Name == "新资产批量调拨单");


            switch (code)
            {
                //新增调拨
                case "NTR":
                    int objectTypeId = 49;
                    bool IsMutiTransfer = false;


                    var condition = new JsonArray();
                    condition.Add(new JsonObject()
                    {
                        ["field"] = "serialNo",
                        ["type"] = "input",
                        ["label"] = "流水号",
                        ["opt"] = "Equal",
                        ["val"] = serialNo
                    });
                    var order = YideaClient.GetCustomizedFormDatas(VformId.Id, new QueryParam() { FilterString = JsonSerializer.Serialize(condition) }).FirstOrDefault();
                    var dataJson = JsonSerializer.Deserialize<JsonObject>(order.Data["datajson"].ToString());
                    string TransferType = dataJson[VTestTransferTypeField.FieldId]?["label"].ToString();
                    //公司内调拨
                    if (TransferType == "公司内调拨")
                    {
                        var result1 = JsonSerializer.Deserialize<List<CrossCompanyResponse>>(resultArray);

                        int flag = 0;
                        string assetError = "";
                        foreach (var item in result1)
                        {
                            if (item.TYPE.ToString() == "S")
                            {
                                flag++;
                            }
                            if (IsMutiTransfer)
                            {
                                //这里是？？
                                //Callback(new CallbackData(CallbackDataType.Asset, transfer.Assets[index].Barcode.ToString(), item.state.ToString()) { ExtraData = new JsonObject() { ["message"] = item.reason.ToString() } });
                            }
                            else
                            {
                                //注释内容不用管
                                //ExecuteCallback(transfer.Assets[index].Barcode.ToString(), "", "", item.state.ToString(), item.reason.ToString());

                            }
                        }
                        string NTRmessage = (flag == result1.Count ? "公司内调拨成功" : (flag == 0 ? "公司内调拨过账失败" : "公司内调拨部分过账"));
                        if (!IsMutiTransfer)
                        {
                            var a = VformId.Id.ToString();
                            var responseData = new JsonObject();
                            var newResultArray = new JsonArray();
                            foreach (var item in resultArray)
                            {
                                // 为每个元素创建副本（根据实际类型处理，如 JsonObject/JsonValue 等）
                                newResultArray.Add(JsonNode.Parse(item.ToJsonString())!);
                            }
                            responseData.Add("result", newResultArray);

                            var b = responseData;
                            b.Add("fromId", a);
                            CallbackHander(new CallbackData(CallbackDataType.CustomizedForm, serialNo, NTRmessage) { ObjectType = objectTypeId, ExtraData = b });
                        }
                    }//公司间调拨
                    else
                    {

                        var result1 = JsonSerializer.Deserialize<List<CrossCompanyResponse>>(resultArray);
                        int successFlag = 0;
                        string retmessage = "", assetError = "";
                        foreach (var item in result1)
                        {
                            if (item.TYPE.ToString().ToUpper() == "S")
                            {
                                successFlag++;
                            }
                            if (result1.Count == 1 && object.ReferenceEquals(item.ZDJBH_IT, null))
                            {
                                successFlag = -1;
                                retmessage = item.MESSAGE.ToString();
                                if (IsMutiTransfer)
                                {
                                    CallbackHander(new CallbackData(CallbackDataType.Asset, "", "-1") { ExtraData = new JsonObject() { ["message"] = retmessage } });
                                }
                            }
                            else
                            {
                                var newbarcode = "";
                                if (!object.ReferenceEquals(item.ANLN1_X, null))
                                {
                                    newbarcode = item.ANLN1_X.ToString().TrimStart('0');
                                }
                                try
                                {
                                    string indexStr = item.ZDJBH_IT.ToString().Trim();
                                    int index = int.Parse(indexStr);
                                    if (IsMutiTransfer)
                                    {
                                        CallbackHander(new CallbackData(CallbackDataType.Asset, item.BarCode.ToString(), item.TYPE.ToString()) { ExtraData = new JsonObject() { ["message"] = item.MESSAGE.ToString(), ["sapCode"] = newbarcode }, ObjectType = 1 });
                                    }
                                    else
                                    {
                                        //ExecuteCallback(transfer.Assets[index - 1].Barcode.ToString(), "", newbarcode, item.TYPE.ToString(), item.MESSAGE.ToString());
                                    }
                                }
                                catch (Exception ex)
                                {
                                    //assetError += ex.ToString();
                                }
                            }
                        }

                        string NTRmessage = (successFlag == result1.Count ? "公司间转移成功" : (successFlag == 0 ? "公司间转移过账失败" : "公司间转移部分过账")) + assetError;
                        if (successFlag == -1)
                        {
                            NTRmessage += "(" + retmessage + ")";
                        }
                        if (!IsMutiTransfer)
                        {
                            var a = VformId.Id.ToString();
                            var responseData = new JsonObject();
                            var newResultArray = new JsonArray();
                            foreach (var item in resultArray)
                            {
                                // 为每个元素创建副本（根据实际类型处理，如 JsonObject/JsonValue 等）
                                newResultArray.Add(JsonNode.Parse(item.ToJsonString())!);
                            }
                            responseData.Add("result", newResultArray);
                            var b = responseData;
                            b.Add("fromId", a);
                            CallbackHander(new CallbackData(CallbackDataType.CustomizedForm, serialNo, NTRmessage) { ObjectType = objectTypeId, ExtraData = b });

                            //CustomerExecuteCallback(userDefine.Id.ToString(), transfer.ExtraData["SerialNo"]!.ToString(), objectTypeId, message);
                        }


                    }

                    break;
                //新资产批量调拨
                case "TRA":
                    var sapCode = ExtendFields.First(x => x.Name == "财务资产编码" && x.ObjectType == 0);
                    var PushStatus = ExtendFields.First(x => x.Name == "推送状态" && x.ObjectType == 0);
                    var PushResult = ExtendFields.First(x => x.Name == "失败原因" && x.ObjectType == 0);
                    var SAPPushStatus = ExtendFields.First(x => x.ObjectType == 62 && x.Name == "SAP推送状态");
                    var tracondition = new JsonArray();
                    tracondition.Add(new JsonObject()
                    {
                        ["field"] = "serialNo",
                        ["type"] = "input",
                        ["label"] = "流水号",
                        ["opt"] = "Equal",
                        ["val"] = serialNo
                    });
                    var traorder = YideaClient.GetCustomizedFormDatas(TRAformId.Id, new QueryParam() { FilterString = JsonSerializer.Serialize(tracondition) }).FirstOrDefault();
                    var TRAdataJson = JsonSerializer.Deserialize<JsonObject>(traorder.Data["dataJson"].ToString());
                    string inComanyCode = string.Empty, outComanyCode = string.Empty;
                    inComanyCode = TRAdataJson[inComanyField.FieldId]?.ToString();
                    outComanyCode = TRAdataJson[outComanyField.FieldId]?.ToString();
                    //判断调拨方式
                    string TRATytpe = (inComanyCode == outComanyCode) ? "公司内调拨" : "公司间调拨";
                    var TRAresult = JsonSerializer.Deserialize<List<CrossCompanyResponse>>(resultArray);
                    if (TRATytpe == "公司内调拨")
                    {
                        int flag = 0; string assetError = "";
                        foreach (var item in TRAresult)
                        {
                            string BarCode = Convert.ToString(item.BarCode);
                            var asset = YideaClient.GetAsset(BarCode);
                            if (item.TYPE.ToString() == "S")
                            {
                                flag++;

                            }
                            try
                            {
                                var assetdataobj = JsonSerializer.Deserialize<JsonObject>(asset.DataJson.ToString());
                                assetdataobj[PushStatus.FieldId] = item.TYPE.ToString();
                                assetdataobj[PushResult.FieldId] = item.MESSAGE.ToString();
                                asset.DataJson = JsonSerializer.Serialize(assetdataobj);
                                bool fals = YideaClient.UpdateAsset(asset, asset);
                                _logger.LogInformation($"批量调拨:[{serialNo}] ,修改资产:[{BarCode}],结果:{fals}");
                            }
                            catch (Exception ex)
                            {

                                throw;
                            }
                        }
                        string message = (flag == TRAresult.Count ? "公司内调拨成功" : (flag == 0 ? "公司内调拨过账失败" : "公司内调拨部分过账"));
                        var NTRcondition = new JsonArray();
                        NTRcondition.Add(new JsonObject()
                        {
                            ["field"] = "serialNo",
                            ["type"] = "input",
                            ["label"] = "流水号",
                            ["opt"] = "Equal",
                            ["val"] = serialNo
                        });
                        var Ntrorder = YideaClient.GetCustomizedFormDatas(TRAformId.Id, new QueryParam { FilterString = JsonSerializer.Serialize(NTRcondition) }).FirstOrDefault();
                        var Ntrdatajson = JsonNode.Parse(Ntrorder.Data["dataJson"].ToString());
                        Ntrdatajson[SAPPushStatus.FieldId] = message;
                        var NTRdata = JsonSerializer.Serialize(Ntrdatajson);
                        UserDefinedForm NTRuserDefinedForm = new UserDefinedForm() { Id = Guid.Parse(Ntrorder.Data["id"].ToString()), SerialNo = serialNo, FormId = TRAformId.Id, JsonData = NTRdata };
                        var updateNTRResponse = YideaClient.UpdateUserDefinedForm(NTRuserDefinedForm, null);
                        _logger.LogInformation($"自定义批量调拨单:【{serialNo}】修改结果" + updateNTRResponse);

                    }
                    //公司间调拨
                    else
                    {
                        int successFlag = 0;
                        string retmessage = "", assetError = "";
                        foreach (var item in TRAresult)
                        {
                            string BarCode = Convert.ToString(item.BarCode);
                            var asset = YideaClient.GetAsset(BarCode);
                            if (item.TYPE.ToString() == "S")
                            {
                                successFlag++;
                            }
                            if (TRAresult.Count == 1 && object.ReferenceEquals(item.ZDJBH_IT, null))
                            {

                                successFlag = -1;
                                retmessage = item.MESSAGE.ToString();
                                var assetdataobj = JsonSerializer.Deserialize<JsonObject>(asset.DataJson.ToString());
                                assetdataobj[PushStatus.FieldId] = "-1";
                                assetdataobj[PushResult.FieldId] = retmessage;
                                asset.DataJson = JsonSerializer.Serialize(assetdataobj);
                                bool falg = YideaClient.UpdateAsset(asset, asset);
                                _logger.LogInformation($"批量调拨:[{serialNo}] ,修改资产:[{BarCode}],结果:{falg}");

                            }
                            else
                            {
                                var newbarcode = "";
                                if (!object.ReferenceEquals(item.ANLN1_X, null))
                                {
                                    newbarcode = item.ANLN1_X.ToString().TrimStart('0');
                                }
                                try
                                {
                                    var assetdataobj = JsonSerializer.Deserialize<JsonObject>(asset.DataJson.ToString());
                                    assetdataobj[sapCode.FieldId] = newbarcode;
                                    assetdataobj[PushStatus.FieldId] = item.TYPE.ToString();
                                    assetdataobj[PushResult.FieldId] = item.MESSAGE.ToString();
                                    asset.DataJson = JsonSerializer.Serialize(assetdataobj);
                                    var falg = YideaClient.UpdateAsset(asset, asset);
                                    _logger.LogInformation($"批量调拨:[{serialNo}] ,修改资产:[{BarCode}],结果:{falg}");

                                }
                                catch (Exception ex)
                                {

                                    throw new Exception($"{ex.Message}");
                                }
                            }
                        }
                        string message = (successFlag == TRAresult.Count ? "公司间转移成功" : (successFlag == 0 ? "公司间转移过账失败" : "公司间转移部分过账"));
                        var NTRcondition = new JsonArray();
                        NTRcondition.Add(new JsonObject()
                        {
                            ["field"] = "serialNo",
                            ["type"] = "input",
                            ["label"] = "流水号",
                            ["opt"] = "Equal",
                            ["val"] = serialNo
                        });
                        var Ntrorder = YideaClient.GetCustomizedFormDatas(TRAformId.Id, new QueryParam { FilterString = JsonSerializer.Serialize(NTRcondition) }).FirstOrDefault();
                        var Ntrdatajson = JsonNode.Parse(Ntrorder.Data["dataJson"].ToString());
                        Ntrdatajson[SAPPushStatus.FieldId] = message;
                        var NTRdata = JsonSerializer.Serialize(Ntrdatajson);
                        UserDefinedForm NTRuserDefinedForm = new UserDefinedForm() { Id = Guid.Parse(Ntrorder.Data["id"].ToString()), SerialNo = serialNo, FormId = TRAformId.Id, JsonData = NTRdata };
                        var updateNTRResponse = YideaClient.UpdateUserDefinedForm(NTRuserDefinedForm, null);
                        _logger.LogInformation($"自定义批量调拨单:【{serialNo}】修改结果" + updateNTRResponse);
                    }


                    break;
                //报废
                case "CLN":
                    UserDefine userDefine = UserDefines.First(x => x.Name == "报废自定义表单");
                    var PushSapStatus = ExtendFields.First(x => x.ObjectType == 48 && x.Name == "sap单据状态");
                    var Clearresult = JsonSerializer.Deserialize<List<CrossCompanyResponse>>(resultArray);
                    int successFlag1 = 0; string assetError1 = "";
                    foreach (var item in Clearresult)
                    {
                        if (item.TYPE.ToString().ToUpper() == "S")
                        {
                            successFlag1++;
                        }
                    }
                    string message1 = (successFlag1 == Clearresult.Count ? "已过账" : (successFlag1 == 0 ? "过账失败" : "部分过账")) + assetError1;
                    var condition1 = new JsonArray();
                    condition1.Add(new JsonObject()
                    {
                        ["field"] = "serialNo",
                        ["type"] = "input",
                        ["label"] = "流水号",
                        ["opt"] = "Equal",
                        ["val"] = serialNo
                    });
                    var order1 = YideaClient.GetCustomizedFormDatas(userDefine.Id, new QueryParam { FilterString = JsonSerializer.Serialize(condition1) }).FirstOrDefault();
                    var datajson1 = JsonNode.Parse(order1.Data["dataJson"].ToString());
                    datajson1[PushSapStatus.FieldId] = message1;
                    var data1 = JsonSerializer.Serialize(datajson1);
                    UserDefinedForm userDefinedForm = new UserDefinedForm() { Id = Guid.Parse(order1.Data["id"].ToString()), SerialNo = order1.Data["serialNo"].ToString(), FormId = userDefine.Id, JsonData = data1 };
                    var updateResponse = YideaClient.UpdateUserDefinedForm(userDefinedForm, null);
                    _logger.LogInformation($"报废单据:【{serialNo}】自定义报废单修改结果" + updateResponse);
                    break;
                //发票登记  
                case "IEF":
                    var IEFuserForm = UserDefines.First(s => s.Name == "发票登记自定义表单");
                    var AssetIntervog = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "sap单据状态");
                    var IEFresult = JsonSerializer.Deserialize<List<InvoiceResponse>>(resultArray);
                    int successFlag2 = 0; string assetError2 = "";
                    foreach (var item in IEFresult)
                    {
                        if (item.TYPE.ToString().ToUpper() == "S")
                        {
                            successFlag2++;
                        }
                        else
                        {
                            assetError2 += item.MESSAGE.ToString() + ";";
                        }
                        try
                        {
                            string indexStr = item.ZDJBH_IT.ToString().Trim();
                            int index = int.Parse(indexStr);
                            ExecuteCallback(item.BarCode.ToString(), "", "", item.TYPE.ToString(), item.MESSAGE.ToString());
                        }
                        catch (Exception ex)
                        {

                            throw new Exception(ex.Message);
                        }

                        //CustomerExecuteCallback(userDefine.Id.ToString(), form.Data["SerialNo"]!.ToString(), 50, message);
                        //修改自定义表达sap单据状态

                    }
                    int length = assetError2.Length > 100 ? 80 : assetError2.Length;
                    string errorMsg = assetError2.Substring(0, length);
                    string IEFmessage = (successFlag2 == IEFresult.Count ? "发票登记过账成功" : (successFlag2 == 0 ? "发票登记过账失败:" : "发票登记部分过账:")) + errorMsg;
                    var IEFcondition2 = new JsonArray();
                    IEFcondition2.Add(new JsonObject()
                    {
                        ["field"] = "serialNo",
                        ["type"] = "input",
                        ["label"] = "流水号",
                        ["opt"] = "Equal",
                        ["val"] = serialNo
                    });
                    var IEForder = YideaClient.GetCustomizedFormDatas(IEFuserForm.Id, new QueryParam { FilterString = JsonSerializer.Serialize(IEFcondition2) }).FirstOrDefault();
                    var IEFdataJson = JsonNode.Parse(IEForder.Data["dataJson"].ToString());
                    IEFdataJson[AssetIntervog.FieldId] = IEFmessage;
                    var IEFdata = JsonSerializer.Serialize(IEFdataJson);
                    UserDefinedForm IEFuserDefinedForm = new UserDefinedForm() { Id = Guid.Parse(IEForder.Id.ToString()), SerialNo = serialNo.ToString(), FormId = IEFuserForm.Id, JsonData = IEFdata };
                    var IEFupdateResponse = YideaClient.UpdateUserDefinedForm(IEFuserDefinedForm, null);
                    _logger.LogInformation($"发票登记单据:【{serialNo}】修改结果" + IEFupdateResponse);
                    int n = 0;
                    break;


            }

        }
        private void ExecuteCallback(string barcode, string data, string fACode, string pushState, string reason)
        {
            //上线要解开
            Thread.Sleep(10000);
            Logger.Info("callback start .." + barcode + "," + data + "," + fACode + "," + pushState + "," + reason);
            var centerCodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "财务资产编码");
            var pushStateField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "推送状态");
            var pushReasonField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "失败原因");
            Logger.Info("callback 中间状态");
            var asset = YideaClient.GetAsset(barcode);
            var oldasset = asset;
            var Jsondata = JsonSerializer.Deserialize<JsonObject>(asset.DataJson);
            //推送状态
            Jsondata![pushStateField.FieldId] = pushState;
            //推送结果
            Jsondata![pushReasonField.FieldId] = reason;
            var dataJson = JsonSerializer.Serialize(Jsondata);
            asset.DataJson = dataJson;
            var falg = YideaClient.UpdateAsset(asset, oldasset);
            if (!falg)
            {
                Logger.Info($"发票登记回写资产信息：{barcode}，回写失败");
            }
            else
            {
                Logger.Info($"发票登记回写资产信息成功：{barcode}，推送状态:[{pushState}],推送结果:[{reason}]");
            }

        }

        /// <summary>
        /// 调拨单回写
        /// </summary>
        /// <param name="data"></param>
        public override void CallbackHander(CallbackData data)
        {
            _logger.LogInformation("开始修改");
            var condition = new JsonArray();
            condition.Add(new JsonObject()
            {
                ["field"] = "serialNo",
                ["type"] = "input",
                ["label"] = "流水号",
                ["opt"] = "Equal",
                ["val"] = data.DataKey
            });
            #region 字段
            //appsetting自定义字段
            var formId = UserDefines.First(x => x.Name == "调拨自定义表单");
            var assetTableField = ExtendFields.First(x => x.ObjectType == 49 && x.Name == "资产列表");
            var assetBarcodeField = ExtendFields.First(x => x.ObjectType == 49 && x.Name == "资产编码");
            var assetAllotField = ExtendFields.First(x => x.ObjectType == 49 && x.Name == "调拨状态");
            var assetSAPField = ExtendFields.First(x => x.ObjectType == 49 && x.Name == "sap单据状态");
            var assetTransferTypeField = ExtendFields.First(x => x.ObjectType == 49 && x.Name == "调拨类型");
            var assetQueryField = ExtendFields.First(x => x.ObjectType == 49 && x.Name == "资产列表query");

            //新调拨单自定义字段
            var VformId = UserDefines.First(x => x.Name == "V测试资产调拨单");
            //var VSAPformId = UserDefines.First(x => x.Name == "SAP字段更新");
            var assetTableField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "资产列表");
            var assetBarcodeField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "资产编码");
            var assetAllotField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调拨状态");
            var assetSAPField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "sap单据状态");
            var assetQueryField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "资产列表query");
            var CunFangDiField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "实际存放地");
            var QuBuField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调入区部");
            var UserField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调入使用人");

            var assetVTestTableField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表");
            var assetVTestBarcodeField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产编码");
            var assetVTestAllotField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试公司间调拨状态");
            var VTestTransferTypeField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调拨类型");
            var assetVTestQueryField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表query");
            var VTestCunFangDiField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试实际存放地");
            var VTestQuBuField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入区部");
            var VTestUserField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入使用人");

            #endregion
            var formIdZong = data.ExtraData["fromId"]!.ToString();
            CustomizedFormData order = new CustomizedFormData();
            var count = 0;

            if (formIdZong == VformId.Id.ToString())
            {
                //获取自定义表单
                order = YideaClient.GetCustomizedFormDatas(VformId.Id, new QueryParam() { FilterString = JsonSerializer.Serialize(condition) }).FirstOrDefault();
                JsonArray assetList = new JsonArray();
                var stringasd = "";
                if (order == null)
                {
                    Console.WriteLine("该单据不存在");
                }
                else
                {
                    //JsonObject newtable = new JsonObject();
                    var datajson = JsonNode.Parse(order.Data["dataJson"].ToString());
                    var TransferType = datajson[VTestTransferTypeField.FieldId]["value"].ToString();
                    //公司内调拨
                    if (TransferType == "公司内调拨")
                    {
                        assetList = datajson[assetTableField2.FieldId].AsArray();
                        datajson[assetSAPField2.FieldId] = data.Data;
                        stringasd = datajson[assetSAPField2.FieldId].ToString();
                        var i = 0;
                        var WriteBackData = data.ExtraData["result"].AsArray();
                        foreach (var item in assetList)
                        {
                            var barcode = item[assetBarcodeField2.FieldId].ToString();

                            var assetTypeCode = "";
                            if (item["assetTypeCode"] == null)
                            {
                                if (item[assetQueryField2.FieldId]["assetTypeCode"] == null)
                                {
                                    var asset = YideaClient.GetAsset(barcode);
                                    if (asset != null)
                                    {
                                        assetTypeCode = asset.AssetTypeCode;
                                    }

                                }
                                else
                                {
                                    assetTypeCode = item[assetQueryField2.FieldId]["assetTypeCode"].ToString();
                                }
                            }
                            else
                            {
                                assetTypeCode = item["assetTypeCode"].ToString();
                            }

                            if (IsPush(assetTypeCode))
                            {
                                var FACodeCode = WriteBackData?[i]?["ANLN1_X"]?.ToString();
                                var AssetCode = WriteBackData[i]?["BarCode"]?.ToString();
                                var Sate = WriteBackData[i]?["TYPE"]?.ToString();
                                var message = WriteBackData[i]?["MESSAGE"]?.ToString();
                                if (Sate == "S")
                                {
                                    item[assetAllotField2.FieldId] = "调拨成功";

                                    count++;
                                }
                                else
                                {
                                    item[assetAllotField2.FieldId] = "调拨失败：" + message;

                                }
                                i++;

                            }
                            else
                            {
                                item[assetAllotField2.FieldId] = "调拨成功";

                                count++;
                            }
                        }
                        datajson[assetTableField2.FieldId] = assetList;

                    }
                    //跨公司调拨
                    else
                    {
                        datajson[assetSAPField2.FieldId] = data.Data;
                        stringasd = datajson[assetSAPField2.FieldId].ToString();
                        assetList = datajson[assetVTestTableField.FieldId].AsArray();
                        var i = 0;
                        var WriteBackData = data.ExtraData["result"].AsArray();
                        foreach (var item in assetList)
                        {
                            var barcode = item[assetVTestBarcodeField.FieldId].ToString();

                            var assetTypeCode = "";
                            if (item["assetTypeCode"] == null)
                            {
                                if (item[assetVTestQueryField.FieldId]["assetTypeCode"] == null)
                                {
                                    var asset = YideaClient.GetAsset(barcode);
                                    if (asset != null)
                                    {
                                        assetTypeCode = asset.AssetTypeCode;
                                    }

                                }
                                else
                                {
                                    assetTypeCode = item[assetVTestQueryField.FieldId]["assetTypeCode"].ToString();
                                }
                            }
                            else
                            {
                                assetTypeCode = item["assetTypeCode"].ToString();
                            }

                            if (IsPush(assetTypeCode))
                            {
                                var Sate = WriteBackData[i]["TYPE"].ToString();
                                var message = WriteBackData[i]["MESSAGE"]?.ToString();
                                var ANLN1 = WriteBackData[i]["ANLN1_X"]?.ToString();
                                if (Sate == "S")
                                {
                                    item[assetVTestAllotField.FieldId] = "调拨成功";

                                    var assetZiChan = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "财务资产编码");
                                    var assetjson = YideaClient.GetAsset(item[assetVTestBarcodeField.FieldId].ToString());
                                    var asdsads = assetjson.DataJson;
                                    JsonObject keyValuePairs = (JsonObject)JsonObject.Parse(asdsads);
                                    keyValuePairs[assetZiChan.FieldId] = ANLN1;
                                    assetjson.DataJson = JsonSerializer.Serialize(keyValuePairs);
                                    YideaClient.UpdateAsset(assetjson, assetjson);

                                    count++;
                                }
                                else
                                {
                                    item[assetVTestAllotField.FieldId] = "调拨失败：" + message;
                                }
                                i++;

                            }
                            else
                            {
                                item[assetVTestAllotField.FieldId] = "调拨成功";
                                count++;
                            }
                        }
                        datajson[assetVTestTableField.FieldId] = assetList;
                    }

                    var data2 = JsonSerializer.Serialize(datajson);

                    //获取自定义表单
                    UserDefinedForm userDefinedForm = new UserDefinedForm() { Id = Guid.Parse(order.Data["id"].ToString()), SerialNo = order.Data["serialNo"].ToString(), FormId = VformId.Id, JsonData = data2 };
                    _logger.LogInformation("参数" + data2);
                    var updateResponse = YideaClient.UpdateUserDefinedForm(userDefinedForm, null);
                    _logger.LogInformation("修改结果" + updateResponse);
                    //生成退库单和领用单
                    if (updateResponse)
                    {
                        if (count != 0 || count <= assetList.Count)
                        {
                            var TuiKu = GenerateRefund(assetList, order, TransferType);
                            if (TuiKu)
                            {
                                _logger.LogInformation("退库单生成成功");
                            }
                            else
                            {
                                _logger.LogInformation("退库单生成失败");
                            }
                            var LingYong = GenerateReceive(assetList, order, TransferType);
                            if (LingYong)
                            {
                                _logger.LogInformation("领用单生成成功");
                            }
                            else
                            {
                                _logger.LogInformation("领用单生成失败");
                            }
                        }
                        else
                        {
                            _logger.LogInformation("该调拨单过账失败或者部分过账");
                        }
                    }
                }
            }
        }
        private bool IsPush(string assetTypeCode)
        {
            string NotPushSap = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "NotPushAssetType").FieldId;
            var code = GetTopAssetTypeCode(assetTypeCode);
            _logger.LogInformation("推送sap资产编码是否推送：" + NotPushSap.Contains("," + code + ","));
            return NotPushSap.Contains("," + code + ",");
        }
        private string GetTopAssetTypeCode(string assetTypeCode)
        {
            List<AssetType> assetTypeList = GetAssetTypeFromCache();
            var assetType = assetTypeList.Where(e => e.Code == assetTypeCode).FirstOrDefault();
            var hierarchyId = assetType.Hierarchy.Split('|')[0];
            int topAssetTypeId = 0;
            int.TryParse(hierarchyId, out topAssetTypeId);
            var topAssetType = assetTypeList.Where(e => e.Id == topAssetTypeId).FirstOrDefault();
            if (topAssetType != null)
            {
                return topAssetType.Code;
            }
            else
            {
                return assetTypeCode;
            }
        }
        private List<AssetType> GetAssetTypeFromCache()
        {
            _cache.TryGetValue("AssetType", out var assetValue);
            List<AssetType> assetTypeList = new List<AssetType>();
            if (assetValue != null)
            {
                assetTypeList = ((IEnumerable<dynamic>)assetValue).Select(item => new AssetType
                {
                    Id = item.Id,
                    Name = item.Name,
                    Hierarchy = item.Hierarchy,
                    Code = item.Code
                }).ToList();
            }
            else
            {
                assetTypeList = FromClient.GetAssetTypes(null).ToList();
                _cache.Set("AssetType", assetTypeList, DateTime.Now.AddMinutes(5));
            }
            return assetTypeList;
        }
        /// <summary>
        /// 生成领用单
        /// </summary>
        /// <returns></returns>
        private bool GenerateReceive(JsonArray assetList, CustomizedFormData order, string TransferType)
        {
            #region 字段
            //新调拨单自定义字段
            var LingYongformId = UserDefines.First(x => x.Name == "新资产领用单");
            var VformId = UserDefines.First(x => x.Name == "V测试资产调拨单");
            var lingCunField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "领用后实际存放地");
            var assetTableField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "资产列表");
            var assetBarcodeField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "资产编码");
            var assetAllotField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调拨状态");
            var assetSAPField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "sap单据状态");
            var assetQueryField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "资产列表query");
            var CunFangDiField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "实际存放地");
            var QuBuField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调入区部");
            var UserField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调入使用人");
            var ChengbenField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入成本中心码");

            var assetVTestTableField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表");
            var assetVTestBarcodeField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产编码");
            var assetVTestAllotField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试公司间调拨状态");
            var VTestTransferTypeField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调拨类型");
            var assetVTestQueryField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表query");
            var VTestCunFangDiField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试实际存放地");
            var VTestQuBuField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入区部");
            var VTestUserField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入使用人");
            var VTestChengBenField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试(公司间)调入成本中心码");


            var DrawAssetDate = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "资产详情");
            var DrawAssetDatequery = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "资产详情query");
            var DrawEmployee = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "员工选择");
            var DrawDepartment = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "部门选择");
            var DrawCunFang = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "存放地大类");
            var DrawDianPu = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "使用店铺");
            var DrawShiJi = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "实际存放地");
            var DrawWuLiu = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "物流信息");
            var DrawBeiZhu = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "备注");
            var DrawShiJiQuery = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "实际存放地query");
            var DrawChenBenCode = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "成本中心代码");


            #endregion
            var btime = "";//修改时间
            JsonArray name = new JsonArray();
            btime = order.Data["modifiedTime"].ToString();
            JsonObject objTui = new JsonObject();
            JsonArray dataValue = new JsonArray();

            foreach (var item in assetList)
            {
                if (TransferType == "公司内调拨" && item[UserField2.FieldId] != null && item[assetAllotField2.FieldId].ToString() == "调拨成功")
                {
                    name.Add(JsonSerializer.Serialize(new { name = item[UserField2.FieldId]!["label"]!.ToString() + item[CunFangDiField2.FieldId]!.ToString() }));
                }
                else if (TransferType == "公司间调拨" && item[VTestUserField.FieldId] != null && item[assetVTestAllotField.FieldId].ToString() == "调拨成功")
                {
                    name.Add(JsonSerializer.Serialize(new { name = item[VTestUserField.FieldId]!["label"]!.ToString() + item[VTestCunFangDiField.FieldId]!.ToString() }));
                }
                else
                {
                    Dictionary<string, object> keys = new Dictionary<string, object>();
                    if (TransferType == "公司内调拨")
                    {
                        keys.Add("调拨方式", TransferType);
                        keys.Add("item[UserField2.FieldId]", item[UserField2.FieldId]);

                        keys.Add("调拨状态", item[assetAllotField2.FieldId].ToString());
                    }
                    if (TransferType == "公司间调拨")
                    {
                        keys.Add("调拨方式", TransferType);
                        keys.Add("item[VTestUserField.FieldId]", item[VTestUserField.FieldId]);
                        keys.Add("调拨状态", item[assetVTestAllotField.FieldId].ToString());
                    }
                    string erStr = JsonSerializer.Serialize(keys);
                    _logger.LogError($"生成自定义领用单--error TransferType:{TransferType}" + erStr);
                }
            }
            var deserializedArray = name.Select(token => JsonSerializer.Deserialize<JsonObject>(token.ToString())).ToList();
            // 使用Distinct方法去重，基于name属性定义去重规则
            var uniqueArray = deserializedArray.DistinctBy(jobject => jobject["name"].ToString()).ToList();
            // 将去重后的JObject列表重新序列化为JSON格式的JToken类型并放入新的JsonArray
            var resultArray = uniqueArray.Select(token => token).ToArray();
            bool ab = false;

            foreach (var item in resultArray)
            {
                var cunfang = "";
                var uservalue = "";//调入使用人value
                var userlabel = "";//调入使用人label
                var usercode = "";//调入使用人code
                var usertype = "";//调入使用人type
                var districtCode = "";//调入区部code
                var c = "";//实际存放地
                string departmentValue = string.Empty;//部门代码value
                var departmentCode = "";//部门代码code
                var departmentLabel = "";//部门代码label
                var departmentType = "";//部门代码type
                var selectcunfangvalue = "";//select实际存放地value
                var selectcunfanglabel = "";//select实际存放地label
                var selectCunDaLeivalue = "";//select存放地大类value
                var selectCunDaLeilabel = "";//select存放地大类label
                var shopName = string.Empty;//店铺名称
                var shopCode = string.Empty;//店铺代码
                var shopValue = string.Empty;//店铺id
                foreach (var itemasset in assetList)
                {
                    var a = "";
                    if (TransferType == "公司内调拨" && itemasset[UserField2.FieldId] != null && itemasset[assetAllotField2.FieldId].ToString() == "调拨成功")
                    {
                        a = itemasset[UserField2.FieldId]["label"]!.ToString() + itemasset[CunFangDiField2.FieldId]!.ToString();

                        var b = item["name"]!.ToString();
                        if (a == b)
                        {

                            JsonObject assetdatajsonling = new JsonObject();
                            assetdatajsonling.Add("id", itemasset["id"]!.GetValue<int>());
                            assetdatajsonling.Add("barcode", itemasset["barcode"]!.ToString());
                            assetdatajsonling.Add("name", itemasset["name"]!.ToString());
                            assetdatajsonling.Add("specs", itemasset["query_1690536112161"]?["specs"]?.ToString());
                            assetdatajsonling.Add("assetTypeName", itemasset["assetTypeName"]!.ToString());
                            //assetdatajsonling.Add("districtName", itemasset["districtName"]!.ToString());
                            assetdatajsonling.Add("select_1692243766053", new JsonObject
                            {
                                ["value"] = itemasset["select_1696820814413"]["value"].ToString(),
                                ["label"] = itemasset["select_1696820814413"]["label"].ToString(),
                                ["color"] = new JsonObject
                                {
                                    ["backgroundColor"] = "#52a8ff",
                                    ["foreColor"] = "#ffffff"
                                }
                            });
                            assetdatajsonling.Add(DrawChenBenCode.FieldId, itemasset[ChengbenField2.FieldId]!.ToString());
                            assetdatajsonling.Add("useCompanyName", itemasset["useCompanyName"]?.ToString());
                            JsonObject queryAble = new JsonObject
                            {
                                [DrawAssetDatequery.FieldId] = assetdatajsonling,
                                ["subId"] = itemasset["subId"]?.ToString(),
                                ["subIndex"] = itemasset["subIndex"].GetValue<int>(),
                                ["version"] = 2
                                //["subIndex"]

                            };

                            dataValue.Add(queryAble);
                            objTui[DrawAssetDate.FieldId] = dataValue;
                            c = itemasset[CunFangDiField2.FieldId]!.ToString();

                            districtCode = itemasset[QuBuField2.FieldId]["value"]!.ToString();
                            uservalue = itemasset["employeeSelect_1695217523213"]?["value"]?.ToString();
                            userlabel = itemasset["employeeSelect_1695217523213"]?["label"]?.ToString();
                            usercode = itemasset["employeeSelect_1695217523213"]?["code"]?.ToString();
                            usertype = itemasset["employeeSelect_1695217523213"]?["type"]?.ToString();
                            departmentValue = itemasset["departmentSelect_1699238334958"]?["value"]?.ToString() ?? string.Empty;
                            departmentCode = itemasset["departmentSelect_1699238334958"]?["code"]?.ToString() ?? string.Empty;
                            departmentLabel = itemasset["departmentSelect_1699238334958"]?["label"]?.ToString() ?? string.Empty;
                            departmentType = itemasset["departmentSelect_1699238334958"]?["type"]?.ToString() ?? string.Empty;
                            selectcunfangvalue = itemasset["select_1732633124408"]?["value"]?.ToString();
                            selectCunDaLeivalue = itemasset["select_1696820814413"]?["value"]?.ToString();
                            selectCunDaLeilabel = itemasset["select_1696820814413"]?["label"]?.ToString();
                            shopName = itemasset["input_1696820941201"]?.ToString() ?? string.Empty;
                            shopCode = itemasset["select_1696820861963"]?["label"]?.ToString() ?? string.Empty;
                            shopValue = itemasset["select_1696820861963"]?["value"]?.ToString() ?? string.Empty;


                        }
                    }
                    else if (TransferType == "公司间调拨" && itemasset[VTestUserField.FieldId] != null && itemasset[assetVTestAllotField.FieldId].ToString() == "调拨成功")
                    {
                        a = itemasset[VTestUserField.FieldId]["label"]!.ToString() + itemasset[VTestCunFangDiField.FieldId]!.ToString();

                        var b = item["name"]!.ToString();
                        if (a == b)
                        {
                            JsonObject assetdatajsonling = new JsonObject();
                            assetdatajsonling.Add("id", itemasset["id"]!.GetValue<int>());
                            assetdatajsonling.Add("barcode", itemasset["barcode"]!.ToString());//资产编码
                            assetdatajsonling.Add("name", itemasset["name"]!.ToString());//资产名称
                            assetdatajsonling.Add("specs", itemasset["specs"]?.ToString());//规格型号
                            assetdatajsonling.Add("assetTypeName", itemasset["assetTypeName"]!.ToString());//资产类别
                            assetdatajsonling.Add(DrawChenBenCode.FieldId, itemasset["input_1691661512030"]?.ToString());//调入成本中心代码
                            assetdatajsonling.Add("useCompanyName", itemasset["useCompanyName"]?.ToString());//使用公司                                         
                            JsonObject queryAble = new JsonObject
                            {
                                [DrawAssetDatequery.FieldId] = assetdatajsonling,
                                ["subId"] = itemasset["subId"]?.ToString(),
                                ["subIndex"] = itemasset["subIndex"].GetValue<int>(),
                                ["version"] = 2
                                //["subIndex"]

                            };

                            dataValue.Add(queryAble);
                            objTui[DrawAssetDate.FieldId] = dataValue;
                            c = itemasset["input_rousootb"]!.ToString();//实际存放地

                            districtCode = itemasset["districtSelect_x60b3v7s"]?["value"]!.ToString();//调入区部code
                            uservalue = itemasset["employeeSelect_dk9ny18k"]?["value"]?.ToString();//使用人value
                            userlabel = itemasset["employeeSelect_dk9ny18k"]?["label"]?.ToString();//使用人label
                            usercode = itemasset["employeeSelect_dk9ny18k"]?["code"]?.ToString();//使用人code
                            usertype = itemasset["employeeSelect_dk9ny18k"]?["type"]?.ToString();//使用人type
                            departmentValue = itemasset["departmentSelect_2t6gk02j"]?["value"]?.ToString() ?? string.Empty;//调入部门value
                            departmentCode = itemasset["departmentSelect_2t6gk02j"]?["code"]?.ToString() ?? string.Empty;//调入部们code
                            departmentLabel = itemasset["departmentSelect_2t6gk02j"]?["label"]?.ToString() ?? string.Empty;//调入部门label
                            departmentType = itemasset["departmentSelect_2t6gk02j"]?["type"]?.ToString() ?? string.Empty;//调入部门type
                                                                                                                         //selectcunfangvalue = itemasset[""]["value"].ToString();

                            selectCunDaLeivalue = itemasset["select_kddqvnb8"]?["value"]?.ToString();
                            selectCunDaLeilabel = itemasset["select_kddqvnb8"]?["label"]?.ToString();
                            selectcunfanglabel = itemasset["input_rousootb"]?.ToString();
                            shopName = itemasset["input_hdjpkhne"]?.ToString() ?? string.Empty;
                            shopCode = itemasset["select_li74i42i"]?["label"]?.ToString() ?? string.Empty;
                            shopValue = itemasset["select_li74i42i"]?["value"]?.ToString() ?? string.Empty;
                        }
                    }
                }

                var opoiubhnij = 11111;
                objTui[DrawShiJi.FieldId] = c;
                objTui[DrawBeiZhu.FieldId] = "本单由调拨单号（" + order.Data["SerialNo"] + "）自动生成";
                objTui[DrawWuLiu.FieldId] = new JsonObject
                {
                    ["value"] = "03",
                    ["label"] = "物流/快递",
                    ["color"] = new JsonObject
                    {
                        ["backgroundColor"] = "#577eff",
                        ["foreColor"] = "#ffffff"
                    }
                };
                objTui[DrawEmployee.FieldId] = new JsonObject
                {
                    ["value"] = uservalue,
                    ["label"] = userlabel,
                    ["code"] = usercode,
                    ["type"] = usertype
                };
                objTui[DrawDepartment.FieldId] = new JsonObject
                {
                    ["value"] = departmentValue,
                    ["label"] = departmentLabel,
                    ["code"] = departmentCode,
                    ["type"] = departmentType
                };

                objTui[DrawCunFang.FieldId] = new JsonObject
                {
                    ["value"] = selectCunDaLeivalue,
                    ["label"] = selectCunDaLeilabel,
                    ["color"] = new JsonObject
                    {
                        ["backgroundColor"] = "#577eff",
                        ["foreColor"] = "#ffffff"
                    }
                };

                //if (TransferType == "公司内调拨")
                //{
                //    objTui[DrawDianPu.FieldId] = new JsonObject
                //    {
                //        ["value"] = selectcunfangvalue,
                //        ["label"] = selectcunfanglabel,
                //        ["color"] = new JsonObject
                //        {
                //            ["backgroundColor"] = "#52a8ff",
                //            ["foreColor"] = "#ffffff"
                //        }
                //    };
                //}
                //else
                //{
                //    objTui[DrawDianPu.FieldId] = selectcunfanglabel;
                //}
                objTui["input_1747725516998"] = shopName;
                objTui["input_1747725500531"] = shopCode;
                objTui["select_1744616605684"] = new JsonObject
                {
                    ["value"] = shopValue,
                    ["label"] = shopCode + " " + shopName,
                    ["color"] = new JsonObject
                    {
                        ["backgroundColor"] = "#52a8ff",
                        ["foreColor"] = "#ffffff"
                    }
                };
                objTui["version"] = "";


                var jsss = JsonSerializer.Serialize(objTui).ToString();

                UserDefinedForm NewDefinedForm = new UserDefinedForm() { FormId = LingYongformId.Id, JsonData = JsonSerializer.Serialize(objTui) };

                if (name.Count == 0)
                {

                    objTui.Clear();
                    dataValue.Clear();
                }
                else
                {
                    ab = YideaClient.AddNewUserDefinedForm(NewDefinedForm);
                    if (ab)
                    {
                        _logger.LogInformation("领用单生成成功");
                        objTui.Clear();
                        dataValue.Clear();
                    }
                    else
                    {
                        _logger.LogInformation("领用单生成失败");
                        objTui.Clear();
                        dataValue.Clear();
                    }

                }
            }

            return ab;
        }


        /// <summary>
        /// 生成退库单
        /// </summary>
        /// <returns></returns>
        private bool GenerateRefund(JsonArray assetList, CustomizedFormData order, string TransferType)
        {
            #region 字段
            //新调拨单自定义字段
            var VformId = UserDefines.First(x => x.Name == "V测试资产调拨单");
            var vsss = UserDefines.First(x => x.Name == "测试退库自定义表单");

            var cunfang1 = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "存放地");
            var useDepart = ExtendFields.First(x => x.ObjectType == 70 && x.Name == "使用部门");
            var shopCode = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "店铺代码");
            var shopName = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "店铺名称");
            var addressBig = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "存放地大类");
            var TuiKuField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "退库后实际存放地");
            var assetTableField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "资产列表");
            var assetBarcodeField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "资产编码");
            var assetAllotField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调拨状态");
            var assetSAPField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "sap单据状态");
            var assetQueryField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "资产列表query");
            var CunFangDiField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "实际存放地");
            var QuBuField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调入区部");
            var UserField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调入使用人");


            var assetVTestTableField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表");
            var assetVTestBarcodeField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产编码");
            var assetVTestAllotField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试公司间调拨状态");
            var VTestTransferTypeField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调拨类型");
            var assetVTestQueryField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表query");
            var VTestCunFangDiField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试实际存放地");
            var VTestQuBuField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入区部");
            var VTestUserField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入使用人");


            //自定义资产退库单
            var customBigcun = ExtendFields.First(x => x.ObjectType == 70 && x.Name == "存放地大类");
            var customCunFang = ExtendFields.First(x => x.ObjectType == 70 && x.Name == "实际存放地");
            var customTuiKu = ExtendFields.First(x => x.ObjectType == 70 && x.Name == "退库配送方式");
            var customAssetdetails = ExtendFields.First(x => x.ObjectType == 70 && x.Name == "资产详情");
            var customAssetList = ExtendFields.First(x => x.ObjectType == 70 && x.Name == "资产列表");
            var customCategory = ExtendFields.First(x => x.ObjectType == 70 && x.Name == "调入存放地大类");
            var remarks = ExtendFields.First(x => x.ObjectType == 70 && x.Name == "退库单备注");

            #endregion

            var btime = "";
            Order OrderJson = new Order();

            btime = order.Data["modifiedTime"].ToString();

            var addressdate = string.Empty;
            var districtCodedate = string.Empty;
            bool qwe = false;

            JsonArray CunFang = new JsonArray();
            JsonObject objTui = new JsonObject();
            JsonArray dataValue = new JsonArray();


            foreach (var item in assetList)
            {
                if (TransferType == "公司内调拨" && item[CunFangDiField2.FieldId] != null && item[assetAllotField2.FieldId].ToString() == "调拨成功")
                {
                    CunFang.Add(JsonSerializer.Serialize(new { CunFang = item[CunFangDiField2.FieldId]!.ToString() }));
                }
                else if (TransferType == "公司间调拨" && item[VTestCunFangDiField.FieldId] != null && item[assetVTestAllotField.FieldId].ToString() == "调拨成功")
                {
                    CunFang.Add(JsonSerializer.Serialize(new { CunFang = item[VTestCunFangDiField.FieldId]!.ToString() }));
                }
                else
                {
                    string str = string.Empty;
                    if (TransferType == "公司内调拨")
                    {
                        str = $"调拨方式:" + TransferType + "，存放地：" + item[CunFangDiField2.FieldId].ToString() + "，调拨状态:" + item[assetAllotField2.FieldId].ToString();
                    }
                    else
                    {
                        str = $"调拨方式:" + TransferType + "，存放地：" + item[VTestCunFangDiField.FieldId].ToString() + "，调拨状态:" + item[assetVTestAllotField.FieldId].ToString();
                    }
                    _logger.LogError($"生成自定义退库单error-——：{str}");
                }


            }



            var deserializedArray = CunFang.Select(token => JsonSerializer.Deserialize<JsonObject>(token.ToString())).ToList();
            // 使用Distinct方法去重，基于name属性定义去重规则
            var uniqueArray = deserializedArray.DistinctBy(jobject => jobject["CunFang"].ToString()).ToList();
            // 将去重后的JObject列表重新序列化为JSON格式的JToken类型并放入新的JsonArray
            var resultArray = uniqueArray.Select(token => token).ToArray();
            var asd = "";
            foreach (var itemqwe in resultArray)
            {
                foreach (var item in assetList)
                {
                    var a = "";
                    if (TransferType == "公司内调拨" && item[assetAllotField2.FieldId].ToString() == "调拨成功")
                    {
                        a = item[CunFangDiField2.FieldId]!.ToString();

                        asd = CunFangDiField2.FieldId;

                        var b = itemqwe["CunFang"]!.ToString();
                        if (a == b)
                        {
                            var assetfrist = YideaClient.GetAsset(item[assetBarcodeField2.FieldId]?.ToString());
                            var asdsads = assetfrist.ManagerEmployeeName;
                            var sadwerq = assetfrist.ManagerEmployeeName;
                            var sate = assetfrist.State;
                            var user = assetfrist.User;
                            addressdate = item[CunFangDiField2.FieldId]!.ToString();
                            districtCodedate = item[QuBuField2.FieldId]["label"]!.ToString();
                            //if (sate == 1 && user != null)
                            //{
                            JsonObject query = new JsonObject()

                            {
                                ["id"] = item["id"]?.GetValue<int>(),
                                //资产编码
                                ["barcode"] = item["barcode"]!.ToString(),
                                //资产名称
                                ["name"] = item[assetQueryField2.FieldId]?["name"]?.ToString(),
                                //使用人
                                ["user"] = item[UserField2.FieldId]?["label"]?.ToString(),
                                //使用部门
                                ["useDepartmentName"] = item[useDepart.FieldId]?["label"]?.ToString() ?? string.Empty,
                                //资产存放地大类                                                                     
                                [addressBig.FieldId] = new JsonObject
                                {
                                    ["value"] = item[customCategory.FieldId]?["value"]?.ToString(),
                                    ["label"] = item[customCategory.FieldId]?["label"]?.ToString(),
                                },
                                //实际存放地
                                [cunfang1.FieldId] = item[CunFangDiField2.FieldId]?.ToString(),
                                //店铺名称
                                [shopName.FieldId] = item[shopName.FieldId]?.ToString() ?? string.Empty,
                                //店铺代码
                                [shopCode.FieldId] = new JsonObject
                                {
                                    ["value"] = item[shopCode.FieldId]?["value"]?.ToString(),
                                    ["label"] = item[shopCode.FieldId]?["label"]?.ToString(),
                                }
                            };
                            objTui[customAssetdetails.FieldId] = dataValue;
                            dataValue.Add(new JsonObject { [customAssetList.FieldId] = query });
                            //退库配送方式 
                            objTui[customTuiKu.FieldId] = new JsonObject
                            {
                                ["value"] = "03",
                                ["label"] = "物流/快递",
                            };
                            //存放地大类
                            objTui[customBigcun.FieldId] = new JsonObject
                            {
                                ["value"] = item[customCategory.FieldId]?["value"]?.ToString(),
                                ["label"] = item[customCategory.FieldId]?["label"]?.ToString(),
                            };
                            //实际存放地
                            objTui[customCunFang.FieldId] = item[CunFangDiField2.FieldId]?.ToString();



                            //}
                        }
                    }
                    else if (TransferType == "公司间调拨" && item[assetVTestAllotField.FieldId].ToString() == "调拨成功")
                    {
                        a = item[VTestCunFangDiField.FieldId]!.ToString();

                        asd = VTestCunFangDiField.FieldId;

                        var b = itemqwe["CunFang"]!.ToString();
                        if (a == b)
                        {
                            var assetfrist = YideaClient.GetAsset(item[assetVTestBarcodeField.FieldId].ToString());
                            var asdsads = assetfrist.ManagerEmployeeName;
                            var sadwerq = assetfrist.ManagerEmployeeName;
                            var sate = assetfrist.State;
                            var user = assetfrist.User;
                            if (sate == 1 && user != null)
                            {

                                JsonObject query = new JsonObject()

                                {
                                    ["id"] = item["id"]?.GetValue<int>(),
                                    //资产编码
                                    ["barcode"] = item["barcode"]!.ToString(),
                                    //资产名称
                                    ["name"] = item["name"]?.ToString(),
                                    //使用人
                                    ["user"] = item["employeeSelect_dk9ny18k"]?["label"]?.ToString(),
                                    //使用部门
                                    ["useDepartmentName"] = item["departmentSelect_2t6gk02j"]?["label"]?.ToString() ?? string.Empty,
                                    //资产存放地大类                                                                     
                                    [addressBig.FieldId] = new JsonObject
                                    {
                                        ["value"] = item["select_kddqvnb8"]?["value"]?.ToString(),
                                        ["label"] = item["select_kddqvnb8"]?["label"]?.ToString(),
                                    },
                                    //实际存放地
                                    [cunfang1.FieldId] = item["input_rousootb"]?.ToString(),
                                    //店铺名称
                                    [shopName.FieldId] = item["input_hdjpkhne"]?.ToString() ?? string.Empty,
                                    //店铺代码
                                    [shopCode.FieldId] = new JsonObject
                                    {
                                        ["value"] = item["select_li74i42i"]?["value"]?.ToString(),
                                        ["label"] = item["select_li74i42i"]?["label"]?.ToString(),
                                    }
                                };
                                objTui[customAssetdetails.FieldId] = dataValue;
                                dataValue.Add(new JsonObject { [customAssetList.FieldId] = query });
                                //退库配送方式 
                                objTui[customTuiKu.FieldId] = new JsonObject
                                {
                                    ["value"] = "03",
                                    ["label"] = "物流/快递",
                                };
                                //存放地大类
                                objTui[customBigcun.FieldId] = new JsonObject
                                {
                                    ["value"] = item["select_kddqvnb8"]?["value"]?.ToString(),
                                    ["label"] = item["select_kddqvnb8"]?["label"]?.ToString(),
                                };
                                //实际存放地
                                objTui[customCunFang.FieldId] = item["input_rousootb"]?.ToString();



                            }
                        }
                    }
                }

                objTui[remarks.FieldId] = "本单由调拨单号（" + order.Data["SerialNo"] + "）自动生成";
                UserDefinedForm newwtui = new UserDefinedForm();
                newwtui.FormId = vsss.Id;
                newwtui.JsonData = JsonSerializer.Serialize(objTui);
                //退库单
                if (dataValue.Count == 0)
                {
                    qwe = false;

                    dataValue.Clear();
                    objTui.Clear();
                }
                else
                {
                    //创建自定义表单
                    qwe = YideaClient.AddNewUserDefinedForm(newwtui);
                    if (qwe)
                    {
                        _logger.LogInformation("退库单生成成功");
                        dataValue.Clear();
                        objTui.Clear();

                    }
                    else
                    {
                        qwe = false;
                        dataValue.Clear();
                        objTui.Clear();
                    }
                }
            }
            return qwe;
        }
    }
}
